var current_tab = '';
function resetPopup() {
	getCurrentTab(tab_id => {
		if(JSON.parse(window.localStorage.getItem('mychromeChecked')||'[]').indexOf(tab_id) > -1) {
			chrome.extension.getViews({type:'popup'})[0].setChecked();
		}
	});
}
chrome.runtime.onConnect.addListener(port => {
	if(port.name == 'status_change') {
		resetPopup();
		port.onMessage.addListener(msg => {
			getCurrentTab(tab_id => {
				var mychrome_checked = JSON.parse(window.localStorage.getItem('mychromeChecked')||'[]');
				if(msg) {
					window.localStorage.setItem('mychromeChecked', JSON.stringify(mychrome_checked.concat([tab_id])));
				}else{
					mychrome_checked.splice(mychrome_checked.indexOf(tab_id), 1);
					window.localStorage.setItem('mychromeChecked', JSON.stringify(mychrome_checked));
				}
			})
		})
	}
})

chrome.webRequest.onCompleted.addListener(function(detail){
	if(/\.(jpg|png|jpeg|icon)/.test(detail.url)) {
		getCurrentTab(tab_id => {
			var port_get_img = chrome.tabs.connect(tab_id, {name: 'get_img_req'});
			port_get_img.postMessage(detail.url);
		})
	}
}, {urls: ["<all_urls>"], types:['image']})

function getCurrentTab(callback) {
	if(current_tab === '') {
		chrome.tabs.query({ active: true }, tabs => {
			var c_tab = tabs[0];
			if(c_tab) {
				current_tab = c_tab.id
				callback(c_tab.id);
			}
		})
	}else{
		callback(current_tab);
	}
}
chrome.tabs.onActivated.addListener(details=> {
	console.log(details.tabId)
	current_tab = details.tabId;
	// chrome.browserAction.setPopup({tabId: details.tabId,popup:'popup.html'});
})